﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lm.Common.ApplicationContext
{
    public static class LogWriter
    {
        static object SyncRoot { get; set; }
        static LogWriter()
        { SyncRoot = new object(); }
        /// <summary>
        /// 此方法是线程安全的
        /// </summary>
        /// <param name="logDir"></param>
        /// <param name="msg"></param>
        public static void Write(string logDir, string msg)
        {
            lock (SyncRoot)
            {
                try
                {
                    logDir += "\\";
                    System.IO.Directory.CreateDirectory(logDir);
                    var fileName = logDir + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, true, Encoding.UTF8))
                    {
                        sw.WriteLine("===" + DateTime.Now.ToString() + "===");
                        sw.WriteLine(msg);
                        sw.WriteLine();
                    }
                }
                catch { }
            }
        }
        /// <summary>
        /// 此方法是线程安全的
        /// </summary>
        /// <param name="msg"></param>
        public static void Write(string msg)
        {
            var logDir = Path.ProgramPath + "\\Log\\";
            LogWriter.Write(logDir, msg);
        }

        public static void Write(Exception ee)
        {
            LogWriter.Write(ee.Message + System.Environment.NewLine + ee.StackTrace);
        }

        public static void WriteForWeb(string msg)
        {
            LogWriter.Write(System.Web.HttpContext.Current.Server.MapPath("/") + "\\log\\", msg);
        }

        public static void WriteForWeb(Exception ee)
        {
            LogWriter.WriteForWeb(ee.Message + System.Environment.NewLine + ee.StackTrace);
        }
    }
}
